package com.group1.ws;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.hibernate.Session;

import com.group1.model.AnswerItem;
import com.group1.model.Question;
import com.group1.model.QuestionImage;
import com.group1.util.SessionFactoryUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.FormDataParam;
import com.sun.jersey.multipart.file.FileDataBodyPart;

@Path("/questionImage")
public class QuestionImageWS {

	private String workingDir;
	
	@GET
	@Path("/getAll")
	@Produces(MediaType.TEXT_PLAIN)
	public String getAllQuestionImage(){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getAllQuestImg(session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + q.getQuestimId() + "\",";
			if(q.getQuestion()!= null)
			{
				result += "\"questID\"" + ":\"" + q.getQuestion().getQuestionId() + "\",";
			}
			else
			{
				result += "\"questID\"" + ":\"" + "\",";
			}
			if(q.getAnswerItem() != null)
			{
				result += "\"answerID\"" + ":\"" + q.getAnswerItem().getAnsiId() + "\",";
			}
			else
			{
				result += "\"answerID\"" + ":\"" + "\",";
			}
			result += "\"questImgLink\"" + ":\"" + q.getQuestimLink() + "\"";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	@GET
	@Path("/getByID/{questImgID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgByID(@PathParam("questImgID") String questImgID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 QuestionImage q = QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session);
		String result;
		result = "{QUESTION_IMG:{";
		result += "\"questImgID\"" + ":\"" + questImgID + "\",";
		if(q.getQuestion()!= null)
		{
			result += "\"questID\"" + ":\"" + q.getQuestion().getQuestionId() + "\",";
		}
		else
		{
			result += "\"questID\"" + ":\"" + "\",";
		}
		if(q.getAnswerItem() != null)
		{
			result += "\"answerID\"" + ":\"" + q.getAnswerItem().getAnsiId() + "\",";
		}
		else
		{
			result += "\"answerID\"" + ":\"" + "\",";
		}
		result += "\"questImgLink\"" + ":\"" + q.getQuestimLink() + "\"";
		result += "}}";
		session.getTransaction().commit();
		return result;
	}
	@GET
	@Path("/getByQuestion/{questID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgQuestion(@PathParam("questID") String questID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getQuestImgByQuestion(Integer.valueOf(questID), session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + q.getQuestimId() + "\",";
			if(q.getQuestion()!= null)
			{
				result += "\"questID\"" + ":\"" + q.getQuestion().getQuestionId() + "\",";
			}
			else
			{
				result += "\"questID\"" + ":\"" + "\",";
			}
			if(q.getAnswerItem() != null)
			{
				result += "\"answerID\"" + ":\"" + q.getAnswerItem().getAnsiId() + "\",";
			}
			else
			{
				result += "\"answerID\"" + ":\"" + "\",";
			}
			result += "\"questImgLink\"" + ":\"" + q.getQuestimLink() + "\"";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	private String ServerPath="D://Workplace//.metadata//.plugins//org.eclipse.wst.server.core//tmp0//wtpwebapps//AssingmentGroup_1//images//";
	@GET
	@Path("/getByAnswer/{answerID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getQuestionImgByAnswer(@PathParam("answerID") String answerID){
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		List<QuestionImage> list = QuestionImage.getQuestImgByAnswer(Integer.valueOf(answerID), session);
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		for (QuestionImage q : list) {
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"questImgID\"" + ":\"" + q.getQuestimId() + "\",";
			if(q.getQuestion()!= null)
			{
				result += "\"questID\"" + ":\"" + q.getQuestion().getQuestionId() + "\",";
			}
			else
			{
				result += "\"questID\"" + ":\"" + "\",";
			}
			if(q.getAnswerItem() != null)
			{
				result += "\"answerID\"" + ":\"" + q.getAnswerItem().getAnsiId() + "\",";
			}
			else
			{
				result += "\"answerID\"" + ":\"" + "\",";
			}
			result += "\"questImgLink\"" + ":\"" + q.getQuestimLink() + "\"";
			result += "}";
		}
		result += "]}";
		session.getTransaction().commit();
		return result;
	}
	
	@GET
	@Path("/GetAllImages/{filePath}")
	@Produces(MediaType.TEXT_PLAIN)
	public String getAllImages(@PathParam("filePath") String filePath){
		filePath=ServerPath;//"D://MITM//New Folder//source//AssingmentGroup_1//WebContent//images";
		String result;
		result = "{QUESTION_IMG:[";
		boolean first = true;
		File folder = new File(filePath);
		File[] listOfFile = folder.listFiles();
		for (File file : listOfFile) {
			result += (first?"":",");
			result += "{";
			first = false;
			result += "\"image\"" + ":\"" + file.getName() + "\"";
			result += "}";
		}
		result += "]}";
		return result;
	}
	
	@GET
	@Path("/create/{questID}/{answerID}/{questImgLink}")
	@Produces(MediaType.TEXT_PLAIN)
	public String createQuestionImg(@PathParam("questID") String questID, @PathParam("answerID") String answerID, 
			@PathParam("questImgLink") String questImgLink)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 	QuestionImage q = new QuestionImage();
			 	if(questID.equals("0"))
			 		q.setAnswerItem(AnswerItem.getAnwserByID(Integer.valueOf(answerID), session));
			 	else
			 		q.setQuestion(Question.getQuestionByID(Integer.valueOf(questID), session));
				q.setQuestimLink(questImgLink);
				session.save(q);
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			session.clear();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	
	@GET
	@Path("/update/{questImgID}/{questID}/{answerID}/{questImgLink}")
	@Produces(MediaType.TEXT_PLAIN)
	public String updateQuestionImg(@PathParam("questImgID") String questImgID,@PathParam("questID") String questID,
			@PathParam("answerID") String answerID,@PathParam("questImgLink") String questImgLink)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 	QuestionImage q = QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session);
			 	if(questID.equals("0"))
			 		q.setAnswerItem(AnswerItem.getAnwserByID(Integer.valueOf(answerID), session));
			 	else
			 		q.setQuestion(Question.getQuestionByID(Integer.valueOf(questID), session));
				q.setQuestimLink(questImgLink);
				session.saveOrUpdate(q);
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			session.clear();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	@GET
	@Path("/delete/{questImgID}")
	@Produces(MediaType.TEXT_PLAIN)
	public String deleteQuestionImg(@PathParam("questImgID") String questImgID)
	{
		Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		 session.beginTransaction();
		 try {
			 session.delete(QuestionImage.getQuestImgByID(Integer.valueOf(questImgID), session));
				session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			session.getTransaction().rollback();
			session.clear();
			return "error: " + e.getMessage();
		}
		 return "success";
	}
	
	@POST
	@Path("/upload")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String uploadImages(@FormDataParam("file") InputStream uploadInputStream,
			@FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String filePath) {
		//return uploadInputStream.toString();
		Properties prop = new Properties();
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())+".JPG";
	   	String uploadFileLocation;
		try {
//			prop.load(new FileInputStream(".//config.properties"));
//			workingDir  = prop.getProperty("ImagePath");
			workingDir=ServerPath;
			uploadFileLocation = workingDir + timeStamp;//fileDetail.getFileName();
			writeToFile(uploadInputStream, uploadFileLocation);
		} catch (Exception e) {
			// TODO: handle exception
			return e.getMessage();
		}
		return timeStamp;
		
	}
	@POST
	@Path("/uploadNew")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String uploadFile(@FormDataParam("file") InputStream uploadInputStream)
	{     
		return uploadInputStream.toString();
		
//		try { 
//			//filePath="D:\\IMG_0064.JPG";
//			Client client = Client.create();
//			 WebResource webResource = client .resource("http://localhost:8080/AssingmentGroup_1/rest/questionImage/upload");
//			 File f = new File(filePath);
//			 FileDataBodyPart fdp = new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE);
//			 FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
//			 formDataMultiPart.bodyPart(fdp); 
//			String reString = webResource.type(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.TEXT_HTML) .post(String.class, formDataMultiPart);
//			return reString;
//			} 
//			catch (Exception e) {
//				return e.getMessage();
//			 }
	
	}

	
	
	private void writeToFile(InputStream uploadedInputStream,
			String uploadedFileLocation) throws IOException {
				File f = new File(uploadedFileLocation);
				OutputStream out = new FileOutputStream(f);
				if(!f.exists())
				{
					f.createNewFile();
				}
				int read = 0;
				byte[] bytes = new byte[1024];
	 
				out = new FileOutputStream(new File(uploadedFileLocation));
				while ((read = uploadedInputStream.read(bytes)) != -1) {
					out.write(bytes, 0, read);
				}
				out.flush();
				out.close();
				}
	
}
